package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

   @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getShopById(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 查询缓存中是否有商铺信息
        String shop = stringRedisTemplate.opsForValue().get(key);
        // 存在 直接返回
        if (shop != null) {
            Shop ShopInfo = null;
            try {
                // 查询出来的id无法转换成Shop就会报错
                ShopInfo = JSONUtil.toBean(shop, Shop.class);
            } catch (Exception e) {
                return Result.fail("店铺信息不存在");
            }
            return Result.ok(ShopInfo);
        }
        // shop == null 缓存不存在 根据查询数据库 写入缓存 返回
        Shop byId = getById(id);

        if (byId == null){
            stringRedisTemplate.opsForValue().set(key,"NULL",CACHE_SHOP_TTL,TimeUnit.MINUTES);
        }
        // 数据库存在写入缓存 返回商品信息 数据库不存在 也写入缓存防止大量请求到db
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(byId),CACHE_SHOP_TTL,TimeUnit.MINUTES);
        return Result.ok(byId);
    }
}
